import service from '@/service.js'
var { DevComm } = require('@/js_sdk/blood/gochek/microtech-devcommIII.mini.js');
const microtechDevComm = DevComm.init();
const getBLEDeviceCharacteristics = (dev,success,extParam=[])=>{
	
	console.log(444444444444444)
	for (let i = 0; i < extParam.services.length; i++) {
	  let service = extParam.services[i]
	  console.log(33333333333333333)
	  console.log('gochek  uuid'+i,service.uuid)
	  console.log('gochek  serviceId'+i,dev.serviceId)
	  if (service.uuid === dev.serviceId) {
	    dev.serviceId = service.uuid;
		console.log(22222222222222)
		_getBLEDeviceCharacteristics(dev,success)
		
	    break;
	  }
	}
	
	
}

function _getBLEDeviceCharacteristics(dev,success){
	console.log(111111111111111)
	uni.getBLEDeviceCharacteristics({
		//设备id与服务id必须要给,特征值id先不用获取，直接写死
		deviceId:dev.deviceId,
		serviceId:dev.serviceId,
		success: (res) => {
			// console.log('蓝牙连接:' + JSON.stringify(res))
			for (let i = 0; i < res.characteristics.length; i++) {
				  let characteristic = res.characteristics[i]
				  dev.characteristicId = characteristic.uuid;
				  uni.notifyBLECharacteristicValueChange({
					deviceId:dev.deviceId,
					serviceId:dev.serviceId,
					characteristicId: dev.characteristicId,
					state: true, //是否启用notify通知
					complete: (res) => {
						console.log('notifyBLECharacteristicValueChange success');
						// if (!this.data.btAvailable) {
						//   return;
						// }
						
						//监听低功耗蓝牙设备的特征值变化事件。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification
						uni.onBLECharacteristicValueChange((characteristic) => {
						
							// console.log('Bluetooth:R: ' + microtechDevComm.hexStringFromArrayBuffer(characteristic.value));
							microtechDevComm.DevComm_Receive(characteristic.value);
						
						})
						bleConnectProcedureComplete(dev.deviceId,dev.serviceId,dev.characteristicId,success)
					
					}
				  })
			}
		},
		fail(res) {
			console.error('获取蓝牙设备特征值失败(getBLEDeviceCharacteristics)', res)
		}
	})
	
}


function initDevComm(deviceId,serviceId,characteristicId,success) {
    // 转换需要发送的数据
    microtechDevComm.DevComm_Send_CallBack((buffer) => {
      dc_send(buffer,deviceId,serviceId,characteristicId);
    })

    // 转换接收到的数据
    microtechDevComm.DevComm_Receive_CallBack((buffer) => {
      dc_receive(buffer,deviceId,success);
      // 终止蓝牙通信信号
      // this.terminateDevCommSession();
      // setTimeout(() => {
      //   this.freeBluetooth();
      // }, 1500);
    })

    // 超时cb
    // microtechDevComm.DevComm_Timeout_CallBack(() => {
    //   // dc_timeout();
    // })
  }
  
 function dc_send(buffer,deviceId,serviceId,characteristicId) {
 
    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId:characteristicId,
      value: buffer,
      complete: (res) => {},
      fail: (res) => {
        console.log('writeBLECharacteristicValue fail')
        console.log(res);
        // that.clearBluetoothTimeout();
        // that.freeBluetooth();

      },
      success: (res) => {
        console.log('writeBLECharacteristicValue success')
      },
    })
  } 
  
  function dc_receive(buffer,deviceId,success) {
    let result = microtechDevComm.getReslultOfRecord(buffer)
	if(result.code==1)
	{
		console.log(result)
		// result.eventIndex  总历史数据     0 为最新测试数据
		// getRecordWithIndex(0,deviceId,success);
		success({
				status: 1,
				code:'onBLECharacteristicValueChange',
				data:{deviceId:deviceId,mol:(result.bloodValue/18).toFixed(1),unit:0,factory:'gocheck'},
				message:'设备测量数据'
			})
	}
		
	
	// console.log('result',result)
   
  }

  
  // 结束蓝牙通信
  function terminateDevCommSession() {
    let r = microtechDevComm.terminateDevCommSession();
    console.log('DevComm_Send: terminate: ' + ' retrurn: ' + r);
    microtechDevComm.DevComm_Clear_State();
  }
  

function  bleConnectProcedureComplete(deviceId,serviceId,characteristicId,success) {
    // 向蓝牙设备发送数据
    initDevComm(deviceId,serviceId,characteristicId,success);
    microtechDevComm.DevComm_Clear_State();
    // getRecordWithIndex(0,deviceId,success);
}
  /**
   * 获取对应index索引的数据
   * @param {number} index 
   * index = 0 获取最新数据
   */
  function  getRecordWithIndex(index,deviceId,success) {
    let r = microtechDevComm.getRecordWithIndex(index);
	console.log(r)
	success({
			status: 1,
			code:'onBLECharacteristicValueChange',
			data:{deviceId:deviceId,mol:r.bloodValue,unit:1,factory:'gocheck'},
			message:'设备测量数据'
		})
    console.log('DevComm_Send: index: ' + index + ' retrurn: ' + r);
  }
export default {
	getBLEDeviceCharacteristics
}